//
//  FmdbAccess.m
//  ebook
//
//  Created by 吴超飞 on 16/3/6.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "FmdbAccess.h"

@implementation FmdbAccess

+ (instancetype)shareModel
{
    static FmdbAccess *model = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        model = [[FmdbAccess alloc] init];
    });
    return model;
}

-(instancetype)init{
    
    self = [super init];
    
    if (self) {
        [self createDefaultTable];
    }
    return self;
}

-(FMDatabaseQueue *)queue{
    if (!_queue) {
        NSString *doc = PATH_OF_DOCUMENT;
        NSString *path = [doc stringByAppendingPathComponent:@"ebook.sqlite"];
        _queue  = [FMDatabaseQueue databaseQueueWithPath:path];
    }
    return _queue;
}

- (void)createDefaultTable {
    
    NSString *sql1 = @"CREATE TABLE 'Bookmark' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL , 'bookid' VARCHAR(30), 'chapterid' VARCHAR(30), 'chaptername'  VARCHAR(50) ,'chapterpercent' float)";
    NSString *sql2 = @"CREATE TABLE 'Booknode' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL , 'bookid' VARCHAR(30), 'chapterid' VARCHAR(30), 'chaptername'  VARCHAR(50) ,'chapterpercent' float)";
    NSString *sql3 = @"CREATE TABLE 'Recommand' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL , 'bookid' VARCHAR(30), 'bookname' VARCHAR(80), 'coverpicurl' VARCHAR(200), 'author'  VARCHAR(50) ,'updatetime' VARCHAR(30), 'firstchapterid' VARCHAR(30), 'firstchaptername' VARCHAR(50),'toptime'  INTEGER ,'valid'  INTEGER default(1), 'fullflag' INTEGER)";
    //dpercent:缓存百分比     rpercent:已读百分比   fullflag:是否完结
    NSString *sql4 = @"CREATE TABLE 'Bookcases' ('bookid' VARCHAR(30) PRIMARY KEY, 'bookname' VARCHAR(80), 'coverpicurl' VARCHAR(200), 'author'  VARCHAR(50) ,'updatetime' VARCHAR(30), 'firstchapterid' VARCHAR(30),'siteid' VARCHAR(10), 'firstchaptername' VARCHAR(50),'toptime'  INTEGER, 'dpercent' float, 'rposition' INTEGER, 'fullflag' INTEGER, 'readingtime' INTEGER default(0),  'chaptercount' INTEGER default(0),'lasthaptercount' INTEGER default(0),'isinnetstore' INTEGER default(0),'display' INTEGER default(0))";
    
    [self.queue inDatabase:^(FMDatabase *db) {
        [self creatTable:@"Bookmark" inDatabase:db withSql:sql1];
        [self creatTable:@"Booknode" inDatabase:db withSql:sql2];
        [self creatTable:@"Recommand" inDatabase:db withSql:sql3];
        [self creatTable:@"Bookcases" inDatabase:db withSql:sql4];
    }];
}

-(BOOL)creatTable:(NSString *)table inDatabase:(FMDatabase *)db withSql:(NSString *)sql {
    
    BOOL suc = NO;
    if ([db open]) {
        if (![db tableExists:table]) {
            suc = [db executeUpdate:sql];
        }else if ([table isEqualToString:@"Recommand"]){
            
            [self addColumnDB:db table:table columnName:@"fullflag" type:@"INTEGER" defaultValue:@"default(0)"];
            [self addColumnDB:db table:table columnName:@"updatetime" type:@"VARCHAR(30)" defaultValue:@"default(0)"];
        } else if ([table isEqualToString:@"Bookcases"]) {
            
            //阅读时间
            [self addColumnDB:db table:table columnName:@"readingtime" type:@"INTEGER" defaultValue:@"default(0)"];
            
            //lasthaptercount:本地书本章节数   chaptercount:服务器端返回的章节数
            [self addColumnDB:db table:table columnName:@"chaptercount" type:@"INTEGER" defaultValue:@"default(0)"];
            [self addColumnDB:db table:table columnName:@"lasthaptercount" type:@"INTEGER" defaultValue:@"default(0)"];
            [self addColumnDB:db table:table columnName:@"updatetime" type:@"VARCHAR(30)" defaultValue:@"default(0)"];
            [self addColumnDB:db table:table columnName:@"rposition" type:@"INTEGER" defaultValue:@"default(0)"];
            [self addColumnDB:db table:table columnName:@"isinnetstore" type:@"INTEGER" defaultValue:@"default(0)"];
            [self addColumnDB:db table:table columnName:@"display" type:@"INTEGER" defaultValue:@"default(0)"];
        }
        [db close];
    }
    return suc;
}

- (void)addColumnDB:(FMDatabase *)db table:(NSString *)table columnName:(NSString *)name type:(NSString *)type defaultValue:(NSString *)defaultValue{
    
    if (![db columnExists:name inTableWithName:table]) {
        NSString *sql = [NSString stringWithFormat:@"ALTER TABLE %@ ADD '%@' %@ %@", table, name, type, defaultValue];
        if ([db executeUpdate:sql]) {
            MTLog(@"FmdbAccess->addColumnDB: insert column %@ success", name);
        } else {
            MTLog(@"FmdbAccess->addColumnDB: insert column fullflag fail");
        }
    }
}

#pragma mark - 书签

-(BOOL)addBookmark:(Bookmark *)mark{
    
    __block BOOL ret = NO;
    if ([self isExistBookmark:mark]) {
        return NO;
    }
    [self.queue inDatabase:^(FMDatabase *db) {
        NSString * sql = @"insert into Bookmark (bookid, chapterid ,chaptername,chapterpercent) values(?, ?, ?, ?) ";
        ret = [db executeUpdate:sql, mark.bookid, mark.chapterid,mark.chaptername, mark.percent ];
        if (!ret) {
            MTLog(@"FmdbAccess->addBookmark: error to insert data");
        }
    }];
    
    return ret;
}

-(BOOL)removeBookmark:(Bookmark *)mark{
    
    __block BOOL ret;
    [self.queue inDatabase:^(FMDatabase *db) {
        
        NSString * sql = @"delete from Bookmark where bookid = ? and chapterid = ? and chapterpercent = ? ";
        ret = [db executeUpdate:sql, mark.bookid, mark.chapterid, mark.percent ];
        if (!ret) {
            MTLog(@"FmdbAccess->removeBookmark:error to delete data");
        }
    }];
    return ret;
}

-(BOOL)isExistBookmark:(Bookmark *)mark{
    
    __block BOOL ret;
    [self.queue inDatabase:^(FMDatabase *db) {
        if([db open]){
            NSString * sql = @"select * from Bookmark where bookid = ? and chapterid = ? and chapterpercent = ? ";
            FMResultSet *rs = [db executeQuery:sql, mark.bookid, mark.chapterid, mark.percent ];
            if (![rs next]) {
                MTLog(@"FmdbAccess->isExistBookmark:error to query data");
                ret = NO;
            } else {
                ret = YES;
            }
            [rs close];
        }
    }];
    return ret;
}

-(void)getBookmarkOfBook:(NSString *)bookid complete:(void(^)(NSMutableArray *books))complete{
    
    [self.queue inDatabase:^(FMDatabase *db) {
        if([db open]){
            NSMutableArray *array = [NSMutableArray array];
            NSString *sql = @"select * from Bookmark where bookid = ?";
            FMResultSet *rs = [db executeQuery:sql,bookid];
            while ([rs next]) {
                NSString *percent = [rs stringForColumn:@"chapterpercent"];
                NSString *chapterid = [rs stringForColumn:@"chapterid"];
                NSString *chaptername = [rs stringForColumn:@"chaptername"];
                
                NSDictionary *dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:bookid?bookid:@"",chapterid?chapterid:@"",chaptername?chaptername:@"",percent?percent:@"", nil] forKeys:[NSArray arrayWithObjects:@"bookid",@"chapterid",@"chaptername",@"percent", nil]];
                Bookmark *mark = [[Bookmark alloc]initWithDictionary:dict];
                
                [array addObject:mark];
            }
            [rs close];
            complete(array);
        }
    }];
}

#pragma mark - 浏览位置

//记录上次浏览位置
-(BOOL)recordBooknode:(Bookmark *)mark{
    
    if(!mark)return NO;
    __block BOOL ret = NO;
    [self.queue inDatabase:^(FMDatabase *db) {
        __strong Bookmark* bookmark = mark;
        if([db open]){
            NSString * sql = @"select * from Booknode where bookid = ? ";
            FMResultSet *rs = [db executeQuery:sql, bookmark.bookid];
            if (![rs next]) {//不存在该书的记录
                
                NSString * sql = @"insert into Booknode (bookid, chapterid ,chaptername, chapterpercent) values(?, ?, ?, ?) ";
                ret = [db executeUpdate:sql, bookmark.bookid, bookmark.chapterid,bookmark.chaptername, bookmark.percent];
                if (!ret) {
                    MTLog(@"FmdbAccess->recordBooknode:error to insert Booknode");
                }
            }else{//直接update
                
                NSString * sql = @"update Booknode set chapterid = ? ,chaptername = ? , chapterpercent =? where bookid = ? ";
                ret = [db executeUpdate:sql, bookmark.chapterid,bookmark.chaptername, bookmark.percent , bookmark.bookid];
                if (!ret) {
                    MTLog(@"FmdbAccess->recordBooknode:error to update Booknode");
                }
            }
            [rs close];
        }
    }];
    
    return ret;
}

//获取上次浏览位置
-(void)getRecordBooknode:(NSString *)bookid complete:(void(^)(Bookmark *booknode))complete{
    
    [self.queue inDatabase:^(FMDatabase *db) {
        if([db open]){
            Bookmark *mark = nil;
            NSString *sql = @"select * from Booknode where bookid = ?";
            FMResultSet *rs = [db executeQuery:sql,bookid];
            while ([rs next]) {
                NSString *percent = [rs stringForColumn:@"chapterpercent"];
                NSString *chapterid = [rs stringForColumn:@"chapterid"];
                NSString *chaptername = [rs stringForColumn:@"chaptername"];
                
                NSDictionary *dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:bookid?bookid:@"",chapterid?chapterid:@"",chaptername?chaptername:@"",percent?percent:@"",  nil] forKeys:[NSArray arrayWithObjects:@"bookid",@"chapterid",@"chaptername",@"percent", nil]];
                
                mark = [[Bookmark alloc]initWithDictionary:dict];
            }
            [rs close];
            complete(mark);
        }
    }];
}

#pragma mark - 推荐
/*
//记录推荐数据  返回值YES：有新数据   NO：没有新数据
-(BOOL)addRecommand:(NSArray *)books{
    
    __block BOOL hasNewData = NO;
    if (!books || books.count == 0)return hasNewData;
    
    [self.queue inDatabase:^(FMDatabase *db) {
        if([db open]){
            for (NSDictionary *dict in books) {
                
                if(!dict||![dict isKindOfClass:[NSDictionary class]])return ;
                Book *book = [[Book alloc]initWithDictionary:dict];
                NSString * sql = @"select * from Recommand where bookid = ? ";
                FMResultSet *rs = [db executeQuery:sql, book.bookid];
                if (![rs next]) {//不存在该书的记录
                    NSString * sql = @"insert into Recommand (bookid,bookname,coverpicurl,author,updatetime,firstchapterid,firstchaptername,toptime,valid,fullflag) values(%@, %@, %@, %@, %@, %@, %@, %d ,%d, %d) ";
                    BOOL res = [db executeUpdateWithFormat:sql, book.bookid, book.bookname,book.coverpicurl, book.author,book.updatetime,book.firstchapterid,book.firstchaptername,[book.toptime intValue],1, book.fullflag];
                    if (!res) {
                        MTLog(@"FmdbAccess->addRecommand:error to insert Recommand");
                    } else {
                        hasNewData = YES;
                    }
                }else{//直接update
                    
                    NSString * sql = @"update Recommand set bookname = %@ ,coverpicurl = %@ ,author = %@ ,updatetime = %@ ,firstchapterid = %@ ,firstchaptername = %@ ,toptime = %d ,fullflag = %d where bookid = %@ ";
                    BOOL res = [db executeUpdateWithFormat:sql, book.bookname,book.coverpicurl, book.author,book.updatetime,book.firstchapterid,book.firstchaptername,[book.toptime intValue] , book.fullflag, book.bookid];
                    if (!res) {
                        MTLog(@"FmdbAccess->addRecommand:error to update Recommand");
                    }
                }
                [rs close];
            }
        }
    }];
    return hasNewData;
}

//获取推荐数据
-(void)getRecomandBooks:(void(^)(NSMutableArray *recommandList))complete{
    
    [self.queue inDatabase:^(FMDatabase *db) {
        
        if([db open]){
            NSMutableArray *array = [NSMutableArray array];
            NSString *sql = @"select * from Recommand where valid = 1 order by toptime desc";
            FMResultSet *rs = [db executeQuery:sql];
            while ([rs next]) {
                NSString *bookid = [rs stringForColumn:@"bookid"];
                NSString *bookname = [rs stringForColumn:@"bookname"];
                NSString *coverpicurl = [rs stringForColumn:@"coverpicurl"];
                NSString *author = [rs stringForColumn:@"author"];
                NSString *updatetime = [rs stringForColumn:@"updatetime"];
                NSString *firstchapterid = [rs stringForColumn:@"firstchapterid"];
                NSString *firstchaptername = [rs stringForColumn:@"firstchaptername"];
                NSString *toptime = [rs stringForColumn:@"toptime"];
                NSString *fullflag = [rs stringForColumn:@"fullflag"];
                
                NSDictionary *dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:bookid?bookid:@"",bookname?bookname:@"",coverpicurl?coverpicurl:@"",author?author:@"",updatetime?updatetime:@"",firstchapterid?firstchapterid:@"",firstchaptername?firstchaptername:@"",toptime?toptime:@"",fullflag?fullflag:@"", nil] forKeys:[NSArray arrayWithObjects:@"bookid",@"bookname",@"coverpicurl",@"author",@"updatetime",@"firstchapterid",@"firstchaptername",@"toptime", @"fullflag", nil]];
                Book *book = [[Book alloc] initWithDictionary:dict];
                
                [array addObject:book];
            }
            [rs close];
            complete(array);
        }
    }];
}

//删除推荐
-(BOOL)removeRecommandBook:(Book *)book{
    
    __block BOOL ret=NO;
    [self.queue inDatabase:^(FMDatabase *db) {
        NSString * sql = @"update Recommand set valid = 0 where bookid = ? ";
        ret = [db executeUpdate:sql, book.bookid ];
        if (!ret) {
            MTLog(@"FmdbAccess->removeRecommandBook:error to update valid = 0");
        }
    }];
    
    return ret;
}

//清空推荐表
-(BOOL)removeAllRecommandBooks {
    
    __block BOOL ret=NO;
    [self.queue inDatabase:^(FMDatabase *db) {
        
        NSString * sql = @"delete from Recommand where  valid = 1";
        ret = [db executeUpdate:sql];
        if (!ret) {
            MTLog(@"FmdbAccess->removeAllRecommandBooks:error to update valid = 0");
        }
    }];
    
    return ret;
}
*/

//删除用户某本书的阅读结点数据
-(BOOL)removeReadBooknode:(NSString *)bookid {
    
    if(!bookid)return NO;
    __block BOOL ret=NO;
    [self.queue inDatabase:^(FMDatabase *db) {
        
        NSString * sql = [NSString stringWithFormat:@"delete from Booknode where bookid = '%@'",bookid];
        ret = [db executeUpdate:sql];
        if (!ret) {
            MTLog(@"FmdbAccess->removeReadBooknode error");
        }
    }];
    
    return ret;
}

-(BOOL)updateBook:(Book *)book forceUpdate:(BOOL)force{
    
    if(!book)return NO;
    
    __block BOOL hasNewData = NO;
    [self.queue inDatabase:^(FMDatabase *db) {
        if([db open]){
            NSString * sql = @"select * from Bookcases where bookid = ? ";
            FMResultSet *rs = [db executeQuery:sql, book.bookid];
            
            NSString *readingtime;
            if (!book.readingtime||book.readingtime.length==0) {
                readingtime = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
            } else {
                readingtime = book.readingtime;
            }
            
            NSString *lasthaptercount = book.lasthaptercount==nil?[rs stringForColumn:@"lasthaptercount"]:book.lasthaptercount;
            if(!lasthaptercount)lasthaptercount = book.chaptercount;
            NSString *rposition = book.rposition;
            rposition = rposition==nil?[rs stringForColumn:@"rposition"]:rposition;
            
            if ([rs next]) {//存在该书的记录.直接update
                
                NSString * sql = @"update Bookcases set bookname = %@ ,coverpicurl = %@ ,author = %@ ,updatetime = %@ ,firstchapterid = %@ ,firstchaptername = %@ ,toptime = %d, dpercent = %f, rposition = %d ,fullflag = %d, readingtime = %@, chaptercount = %@, lasthaptercount = %@, display = %@,siteid = %@ where bookid = %@ ";
                BOOL res = [db executeUpdateWithFormat:sql, book.bookname,book.coverpicurl, book.author,book.updatetime,book.firstchapterid,book.firstchaptername,[book.toptime intValue], [book.dpercent floatValue], [rposition intValue], [book.fullflag intValue], readingtime, book.chaptercount, lasthaptercount, book.display, book.bookid,book.siteid];
                
                if (!res) {
                    MTLog(@"FmdbAccess->updateBook:error to update Bookcases");
                } else {
                    hasNewData = YES;
                }
            }else if(force){
                
                NSString * sql = @"insert into Bookcases (bookid,bookname,coverpicurl,author,updatetime,firstchapterid,firstchaptername,toptime,dpercent,rposition,fullflag, readingtime, chaptercount, lasthaptercount, display, siteid) values(%@, %@, %@, %@, %@, %@, %@, %d, %f, %d, %d, %@, %@, %@, %@, %@) ";
                BOOL res = [db executeUpdateWithFormat:sql, book.bookid, book.bookname,book.coverpicurl, book.author,book.updatetime,book.firstchapterid,book.firstchaptername,[book.toptime intValue],[book.dpercent floatValue], [rposition intValue], [book.fullflag intValue],readingtime, book.chaptercount, lasthaptercount, book.display, book.siteid];
                
                if (!res) {
                    MTLog(@"FmdbAccess->updateBook:error to insert Bookcases");
                } else {
                    hasNewData = YES;
                }
                
            }
            [rs close];
        }
    }];
    
    return hasNewData;
}

#pragma mark - 书架
//记录书架图书数据
-(BOOL)addBookcase:(NSArray *)books {
    
    __block BOOL hasNewData = NO;
    if (!books || books.count == 0)return hasNewData;
    [self.queue inDatabase:^(FMDatabase *db) {
        
        if([db open]){
            
            for (Book *book in books) {
                
                if(!book.bookid||book.bookid.length==0)continue;
                NSString * sql = @"select * from Bookcases where bookid = ? ";
                FMResultSet *rs = [db executeQuery:sql, book.bookid];
                if (![rs next]) {//不存在该书的记录
                    
                    if(!book.lasthaptercount||book.lasthaptercount==0)//新加书架时，两个值设置成相同
                        book.lasthaptercount=book.chaptercount;
                    NSString * sql = @"insert into Bookcases (bookid,bookname,coverpicurl,author,updatetime,firstchapterid,firstchaptername,toptime,dpercent,rposition,fullflag,readingtime, lasthaptercount, chaptercount, display, siteid) values(%@, %@, %@, %@, %@, %@, %@, %d, %f, %d, %d, %@, %d, %d, %d, %@) ";
                    BOOL res = [db executeUpdateWithFormat:sql, book.bookid, book.bookname,book.coverpicurl, book.author,book.updatetime,book.firstchapterid,book.firstchaptername,[book.toptime intValue],[book.dpercent floatValue], [book.rposition intValue], [book.fullflag intValue], book.readingtime, [book.lasthaptercount intValue], [book.chaptercount intValue],[book.display intValue],book.siteid];
                    if (!res) {
                        MTLog(@"FmdbAccess->addBookcase:error to insert Bookcases");
                    } else {
                        hasNewData = YES;
                    }
                }else{//直接update
                    
                    NSString * sql = @"update Bookcases set bookname = %@, coverpicurl = %@, author = %@, updatetime = %@, firstchapterid = %@, firstchaptername = %@, toptime = %d, dpercent = %f, rposition = %d, fullflag = %d, readingtime = %@, lasthaptercount = %d, chaptercount = %d, display = %d  where bookid = %@ ";
                    
                    //如果不是特意更新某字断（值不为空），则维持原值不变
                    NSString *lasthaptercount = book.lasthaptercount==nil?[rs stringForColumn:@"lasthaptercount"]:book.lasthaptercount;
                    if(!lasthaptercount)lasthaptercount = book.chaptercount;
                    NSString *rposition = book.rposition;
                    rposition = rposition==nil?[rs stringForColumn:@"rposition"]:rposition;
                    NSString *readingtime = book.readingtime;
                    readingtime = readingtime==nil?[rs stringForColumn:@"readingtime"]:readingtime;
                    
                    BOOL res = [db executeUpdateWithFormat:sql, book.bookname,book.coverpicurl, book.author,book.updatetime,book.firstchapterid,book.firstchaptername,[book.toptime intValue], [book.dpercent floatValue], [rposition intValue], [book.fullflag intValue], readingtime, [lasthaptercount intValue], [book.chaptercount intValue],[book.display intValue], book.bookid];
                    if (!res) {
                        MTLog(@"FmdbAccess->addBookcase:error to update Bookcases");
                    } else {
                        if ([[rs stringForColumn:@"chaptercount"] intValue]!=[book.chaptercount intValue]) {
                            hasNewData = YES;
                        }
                    }
                }
                [rs close];
            }
        }
    }];
    return hasNewData;
}

//获取书架图书数据
-(void)getBookcases:(void(^)(NSMutableArray *casebooks))complete {
    
    [self.queue inDatabase:^(FMDatabase *db) {
        
        if([db open]){
            NSMutableArray *array = [NSMutableArray array];
            
            NSString *sql = @"select * from Bookcases order by readingtime desc";
            FMResultSet *rs = [db executeQuery:sql];
            while ([rs next]) {
                NSString *bookid = [rs stringForColumn:@"bookid"];
                NSString *bookname = [rs stringForColumn:@"bookname"];
                NSString *coverpicurl = [rs stringForColumn:@"coverpicurl"];
                NSString *author = [rs stringForColumn:@"author"];
                NSString *updatetime = [rs stringForColumn:@"updatetime"];
                NSString *firstchapterid = [rs stringForColumn:@"firstchapterid"];
                NSString *firstchaptername = [rs stringForColumn:@"firstchaptername"];
                NSString *toptime = [rs stringForColumn:@"toptime"];
                NSString *dpercent = [rs stringForColumn:@"dpercent"];
                NSString *rposition = [rs stringForColumn:@"rposition"];
                NSString *fullflag = [rs stringForColumn:@"fullflag"];
                NSString *time = [rs stringForColumn:@"readingtime"];
                NSString *localtotal = [rs stringForColumn:@"lasthaptercount"];
                NSString *servertotal = [rs stringForColumn:@"chaptercount"];
                NSString *isinnetstore = [rs stringForColumn:@"isinnetstore"];
                NSString *display = [rs stringForColumn:@"display"];
                NSString *siteid = [rs stringForColumn:@"siteid"];
                
                NSDictionary *dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:bookid?bookid:@"",bookname?bookname:@"",coverpicurl?coverpicurl:@"",author?author:@"",updatetime?updatetime:@"",firstchapterid?firstchapterid:@"",firstchaptername?firstchaptername:@"",toptime?toptime:@"", dpercent?dpercent:@"", rposition?rposition:@"",fullflag?fullflag:@"", time?time:@"", localtotal?localtotal:@"", servertotal?servertotal:@"", isinnetstore, display?display:@"",siteid?siteid:@"", nil] forKeys:[NSArray arrayWithObjects:@"bookid",@"bookname",@"coverpicurl",@"author",@"lastupdate",@"firstchapterid",@"firstchaptername",@"toptime", @"dpercent", @"rposition", @"fullflag", @"readingtime", @"lasthaptercount", @"chaptercount", @"isinnetstore", @"display",@"siteid", nil]];
                Book *book = [[Book alloc] initWithDictionary:dict];
                
                if([book.bookid intValue]>0 && book.bookname.length>0)
                    [array addObject:book];
            }
            
            if([[NSUserDefaults standardUserDefaults] boolForKey:kIsShowRecentRead]){//如果显示最近阅读视图，则注意需要将最近阅读的那本书放在第一位
                int firstReadIndex = 0;//找出最近阅读的那本书
                for (int i=0; i<array.count; i++) {
                    Book *book = [array objectAtIndex:i];
                    if ([book.rposition intValue]!=0) {
                        firstReadIndex = i;
                        break;
                    }
                }
                [array exchangeObjectAtIndex:0 withObjectAtIndex:firstReadIndex];//将最近阅读的那本书放在第一位（如果存在）
            }
            [rs close];
            complete(array);
        }
    }];
}

//删除书架某一本图书
-(BOOL)removeBookcase:(NSString *)bookid {
    
    __block BOOL ret=NO;
    [self.queue inDatabase:^(FMDatabase *db) {
        
        NSString * sql = [NSString stringWithFormat:@"delete from Bookcases where bookid = '%@'",bookid];
        ret = [db executeUpdate:sql];
        if (!ret) {
            MTLog(@"FmdbAccess->removeBookcase:error to remove book");
        }
    }];
    
    return ret;
}

//清空书架数据
-(BOOL)clearBookcase{
    
    __block BOOL ret=NO;
    [self.queue inDatabase:^(FMDatabase *db) {
        
        NSString * sql = [NSString stringWithFormat:@"delete from Bookcases"];
        ret = [db executeUpdate:sql];
        if (!ret) {
            MTLog(@"FmdbAccess->clearBookcase:error");
        }
    }];
    
    return ret;
}

@end
